#!/bin/python
#--coding: utf-8 -*-
import sys
sys.path.append("..")

import utils.raster as raster
import utils.common as common
import math
import numpy as np
import os
import re


def compose_wind_speed(u,v):
	return np.sqrt(np.square(u)+np.square(v))

def get_wind_direction(u,v):
	# tmp = (3 * np.pi / 2 - np.arctan2(v,u)) * 180 / np.pi
	tmp = (np.pi  + np.arctan2(u,v)) * 180 / np.pi
	tmp = np.ma.array(tmp,mask = ((u == 0) & (v < 0)),fill_value = 0)
	return np.ma.array(tmp,mask = ((u == 0) & (v == 0)),fill_value = -999.0)

def wind_vector(u,v):
	return compose_wind_speed(u,v),get_wind_direction(u,v)

if __name__ == '__main__':
	path = "/mnt/fire/Extract"
	b = 17.502
	c = 240.97
	for root,dirs,files in os.walk(os.path.join(path,"t2m")):
		for file in files:
			if file.endswith(".tif"):
				# u_info,u = raster.open(os.path.join(root,file))
				# v_info,v = raster.open(os.path.join(os.path.join(path,"v10","v%s"%file[1:])))
				# (wns,wnd) = wind_vector(u,v)

				# out_wns_path = os.path.join(path,"wns")
				# common.is_exists(out_wns_path)

				# out_wnd_path = os.path.join(path,"wnd")
				# common.is_exists(out_wnd_path)

				# raster.save(os.path.join(out_wns_path,"wns_%s"%file[4:]),wns,-999.0,u_info[1],u_info[2])
				# raster.save(os.path.join(out_wnd_path,"wnd_%s"%file[4:]),wnd,-999.0,u_info[1],u_info[2])
				t2m_info,t2m = raster.open(os.path.join(root,file))
				d2m_info,d2m = raster.open(os.path.join(os.path.join(path,"d2m","d2m%s"%file[3:])))

				rh = 100 * (np.exp((b * (d2m- 273.15))/(c + d2m -  273.15))) / (np.exp((b *  (t2m- 273.15)) / (c + t2m-273.15)))
				out_wnd_path = os.path.join(path,"rh")
				common.is_exists(out_wnd_path)
				raster.save(os.path.join(out_wnd_path,"rh_%s"%file[4:]),rh,-999.0,d2m_info[1],d2m_info[2])
